package com.king.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.code.kaptcha.Producer;
import com.king.common.lang.Result;
import com.king.entity.MUser;
import com.king.util.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@Controller
public class AuthController extends BaseController {

    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";

    @Autowired
    Producer producer;

    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response) throws IOException {
        String yzm = producer.createText();//验证码
        BufferedImage image = producer.createImage(yzm);

        request.getSession().setAttribute(KAPTCHA_SESSION_KEY, yzm);

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
    }

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @ResponseBody
    @PostMapping("/login")
    public Result doLogin(String email, String password) {
        if (StrUtil.isBlank(email) || StrUtil.isBlank(password)) {
            return Result.fail("用户名、密码不能为空！");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(email, SecureUtil.md5(password));
        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            String errMsg = "用户认证失败！";
            if (e instanceof UnknownAccountException) {
                errMsg = "用户不存在！";
            } else if (e instanceof LockedAccountException) {
                errMsg = "用户被禁用！";
            } else if (e instanceof IncorrectCredentialsException) {
                errMsg = "密码错误哦！";
            }

            return Result.fail(errMsg);
        }

        return Result.success().action("/");
    }

    @GetMapping("/register")
    public String register() {
        return "/auth/reg";
    }

    @ResponseBody
    @PostMapping("/register")
    public Result doRegister(MUser user, String repass, String vercode) {
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(user);
        if (validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }

        if (!user.getPassword().equals(repass)) {
            return Result.fail("两次密码不一致！");
        }

        String kaptcha = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        log.info("auth kaptcha -->: "+ kaptcha);
        if (StringUtils.isBlank(vercode) || !kaptcha.equalsIgnoreCase(vercode)) {
            return Result.fail("验证码不正确！");
        }

        Result result = mUserService.register(user);

        return result.action("/login");
    }

    @GetMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/";//退出后，重定向到首页
    }
}
